package walk
{
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.filters.DropShadowFilter;
	import flash.filters.GlowFilter;
	import flash.geom.Point;
	import flash.media.Video;
	import flash.net.ObjectEncoding;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	import io.Global;
	import io.Packet;
	import io.PacketBuffer;
	import io.People;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.core.UIComponent;
	import mx.utils.UIDUtil;
	
	public class GameMap extends BaseDisplayObject
	{
		private var people:People = new People;
		
		private var _player:HeptaFishCharacter;//人物
		private var _players:Array = [];//其他队员
		
		private var _initPlayerPoint:Point =  new Point(30,80);//初始时人物坐标
		
		private var _app:UIComponent;
		
		private var _plaerLoader:ImageLoader;
		
		private var _bitMap:Bitmap;
		
		private var socket:Socket = new Socket();
		
		public function GameMap(app:UIComponent)
		{
			this._app = app;
			this._app.addChild(this);
			byteBuffer = new ByteArray;
			byteBuffer.objectEncoding = ObjectEncoding.AMF3;
			_plaerLoader = new ImageLoader();
			_plaerLoader.load("walk/woman.png");
			_plaerLoader.addEventListener(Event.COMPLETE,manLoaded);
			this.filters = [
				new GlowFilter(0x88AEF7,1,12,12,2,2),
				new DropShadowFilter() 
			];
		}
		
		protected function connect(e:Event):void{
			//Alert.show("已经建立连接....");
			//Alert.show(_player.people.id);
			send_data(_player.people,"addPlay");
		}
		
		protected function close(e:Event):void{
			Alert.show("已经断开连接....");
		}
		
		public function send_data(people:Object,method:String):void{
			var arr:ByteArray = new ByteArray();
			var p:Packet = Global.instance().packageData(people,method);
			arr.writeObject(p);
			arr.compress();
			var data:ByteArray = new ByteArray;
			data.writeInt(arr.length);
			data.writeBytes(arr,0,arr.length);
			socket.writeBytes(data,0,data.length);	
			socket.flush();
		}
		
		
		private var buffer:PacketBuffer = new PacketBuffer;
		
		protected function socket_data(e:ProgressEvent):void{
			try{
				
				parse();
				
				//								var temBytes:ByteArray = new ByteArray();
				//								socket.readBytes(temBytes,0,e.bytesTotal);
				//								buffer.push(temBytes);
				//								var packets:Array = buffer.getPackets();
				//								for each(var packet:Packet in packets){
				//									var data:Object = Global.instance().unPackageData(packet);
				//									//解析数据了
				//									if(data is People){
				//										var people:People =  data as People;
				//										if(people.id == _player.people.id){
				//											return
				//										}else{
				//											if(people.action == 0)
				//											{
				//												for each(var char:HeptaFishCharacter in _players){
				//													if(char.people.id == people.id){
				//														if(char.people.x != people.x || char.people.y != people.y)
				//															char.moveTo(people.x,people.y);
				//													}
				//												}
				//											}else if(people.action == 1){
				//												var heptaFishCharacter:HeptaFishCharacter = new HeptaFishCharacter(_bitMap,true,10,5,2,0,0,1,0);
				//												heptaFishCharacter.name = "player:"+ UIDUtil.createUID() ;
				//												heptaFishCharacter.map = this;
				//												heptaFishCharacter.people = people;
				//												_players.push(heptaFishCharacter);
				//												this.addPlayer(heptaFishCharacter,true);
				//											}
				//										}
				//									}else if(data is Array){
				//										var peoples:Array = data as Array;
				//										for each(var p:People in peoples){
				//											var heptaFishCharacter:HeptaFishCharacter = new HeptaFishCharacter(_bitMap,true,10,5,2,0,0,1,0);
				//											heptaFishCharacter.name = "player:"+ UIDUtil.createUID() ;
				//											heptaFishCharacter.map = this;
				//											heptaFishCharacter.people = p;
				//											heptaFishCharacter.x = p.x;
				//											heptaFishCharacter.y = p.y;
				//											_players.push(heptaFishCharacter);
				//											this.addPlayer(heptaFishCharacter);
				//										}
				//									}
				//								}
			}catch(error:Error){
				Alert.show("Error: " + error.message);
			}
		}
		
		/**
		 * 正确的读取方法
		 */
		private var byteBuffer:ByteArray;	//数据缓存
		private var dataLength:int;			//接收到的数据长度
		private var headLen:int = 4;		//数据包首部长度
		private function parse():void{
			try{
				//开始读取数据的标记
				var readFlag:Boolean = false;
				//每读取一条数据bytesAvailable值将随之减少
				//while (socket.bytesAvailable>=headLen) {
				while (socket.bytesAvailable) {
					if (!readFlag && socket.bytesAvailable >= headLen) {
						//读取数据长度
						dataLength = socket.readInt();
						readFlag = true;
					}
					//如果为0,表示收到异常消息，避免无限循环地等待
					if(dataLength==0){
						//dispatchEvent(new NetEvent(NetEvent.NULL_STREAM));
						//Alert.show("收到异常消息","Error");
						return;
					}
					//数据流里的数据满足条件，开始读数据
					if (readFlag && socket.bytesAvailable >= dataLength){
						//指针回归
						byteBuffer.position = 0;
						//取出指定长度的字节
						//读取完一条消息后发送消息内容
						socket.readBytes(byteBuffer, 0, dataLength);
						byteBuffer.uncompress();
						var data:Object = Global.instance().unPackageData(byteBuffer.readObject() as Packet);
						//解析数据了
						if(data is People){
							var people:People =  data as People;
							if(people.id == _player.people.id){
								return
							}else{
								if(people.action == 0)
								{
									for each(var char:HeptaFishCharacter in _players){
										if(char.people.id == people.id){
											if(char.people.x != people.x || char.people.y != people.y)
												char.moveTo(people.x,people.y);
										}
									}
								}else if(people.action == 1){
									var heptaFishCharacter:HeptaFishCharacter = new HeptaFishCharacter(_bitMap,true,10,5,2,0,0,1,0);
									heptaFishCharacter.name = "player:"+ UIDUtil.createUID() ;
									heptaFishCharacter.map = this;
									heptaFishCharacter.people = people;
									_players.push(heptaFishCharacter);
									this.addPlayer(heptaFishCharacter,true);
								}
							}
						}else if(data is Array){
							var peoples:Array = data as Array;
							for each(var p:People in peoples){
								var heptaFishCharacter:HeptaFishCharacter = new HeptaFishCharacter(_bitMap,true,10,5,2,0,0,1,0);
								heptaFishCharacter.name = "player:"+ UIDUtil.createUID() ;
								heptaFishCharacter.map = this;
								heptaFishCharacter.people = p;
								heptaFishCharacter.x = p.x;
								heptaFishCharacter.y = p.y;
								_players.push(heptaFishCharacter);
								this.addPlayer(heptaFishCharacter);
							}
						}
						//var event:NetEvent=new NetEvent(NetEvent.READED_DATA);
						//event.bytesData=byteBuffer;
						//dispatchEvent(event);
						dataLength = 0;
						readFlag = false;
					}
				}
			}catch(e:Error){
				
			}
		}
		
		private function manLoaded(evet:Event):void{
			//初始化人物
			_bitMap = new Bitmap(_plaerLoader._data);
			var image:Bitmap = new Bitmap(new BitmapData(_app.width,_app.height,true));
			this.addChild(image);
			creatPlayer();
			
			socket.objectEncoding = ObjectEncoding.AMF3;
			socket.connect("192.168.1.15",9099);
			socket.addEventListener(Event.CONNECT,connect);
			socket.addEventListener(Event.CLOSE,close);
			addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void{
				Alert.show("IO错误")				
			});
			addEventListener(SecurityErrorEvent.SECURITY_ERROR,function(e:SecurityErrorEvent):void{
				Alert.show("Security错误");				
			});
			socket.addEventListener(ProgressEvent.SOCKET_DATA,socket_data);
		}
		
		private function creatPlayer():void{
			_player = new HeptaFishCharacter(_bitMap,true,10,5,2,0,0,1,0);
			_player.name = "player:"+ UIDUtil.createUID() ;
			_player.people = new People();
			_player.map = this;
			this.addEventListener(MouseEvent.CLICK,this.onClick);
			this.addPlayer(_player,true);
		}
		
		//加入用户角色
		public function addPlayer(_player:HeptaFishCharacter,initPoint:Boolean = false):void{
			_player.mapEle = this;
			if(initPoint){
				_player.x = _initPlayerPoint.x;
				_player.y = _initPlayerPoint.y;
			}
			//addItem(player);
			this.addChild(_player as DisplayObject);
		}
		//地图层加载完成
		private function mapLayerLoaded(evet:Event):void{
			
		}
		//地图点击事件
		public function onClick(event:Event):void{
			_player.people.action = 0;
			_player.people.x = event.currentTarget.mouseX;
			_player.people.y = event.currentTarget.mouseY + 15;
			send_data(_player.people,"synXY");
			//									var timer:Timer = new Timer(50);
			//									timer.addEventListener(TimerEvent.TIMER,function(e:Event):void{
			//										send_data(_player.people,"synXY");
			//									});
			//									timer.start();
			_player.addEventListener(WalkEvent.WALK_END, onMoveOver);
			_player.addEventListener(WalkEvent.ON_WALK,checkDep);
			_player.moveTo(event.currentTarget.mouseX, event.currentTarget.mouseY + 15);
		}
		//一段路程移动完成
		protected function onMoveOver(event:Event):void{
			//			var player:HeptaFishCharacter = event.target as HeptaFishCharacter;
			//			if(_pathIndex<_roadArr.length-1){
			//				_pathIndex++;
			//				if(_pathIndex==_roadArr.length){
			//					player.moveTo(player.moveToX, player.moveToY);
			//				}else{
			//					var px:int =  _roadMap.getValue(_roadSeeker.path[_pathIndex].y+"-"+_roadSeeker.path[_pathIndex].x).px;
			//					var py:int =  _roadMap.getValue(_roadSeeker.path[_pathIndex].y+"-"+_roadSeeker.path[_pathIndex].x).py;
			//					_player.addEventListener(WalkEvent.WALK_END, onMoveOver);
			//					var tp:Point = GameMapUtils.getPixelPoint(_cellWidth,_cellHeight,px,py);
			//					_player.moveTo(tp.x, tp.y+_cellHeight);
			//				}
			//			}else{
			_player.removeEventListener(WalkEvent.WALK_END, onMoveOver);
			//			}
		}
		//移动中 检查深度
		private function checkDep(evet:WalkEvent):void{
			//			for each(var bl:* in _buildLayer.buildingArray){
			//				if(bl is GameMapItem){
			//					if(bl.bitMap.hitTestObject(_player as DisplayObject)){
			////						trace(2);
			//						if(_player.y < bl.y + bl.bitMap.height){
			//							if(_buildLayer.getChildIndex(_player as DisplayObject) > _buildLayer.getChildIndex(bl)){
			//								_buildLayer.swapChildren(_player as DisplayObject, bl);
			////								var rect:Rectangle = new Rectangle(_player.x, _player.y, _player.width, _player.height);
			////								var pt:Point = new Point(0,0);
			////								_player.filter.threshold(bl.bitMap.bitmapData, rect, pt, ">", 0x00000000, 0x80000000);
			////								_player.bitmap.bitmapData.copyPixels(_player.bitmap.bitmapData, _player.rect, pt, _player.filter, pt, false);
			//								
			//							}
			//						}else{
			//							if(_buildLayer.getChildIndex(_player as DisplayObject) < _buildLayer.getChildIndex(bl)){
			//								_buildLayer.swapChildren(_player as DisplayObject, bl);
			//							}
			//						}
			//					}
			//				}
			//			}
		}
	}
}